/**
 * 
 */
package com.hk.Mgr.web.controller.common;

import com.hk.Mgr.web.message.StatusCode;
import com.hk.Mgr.web.message.order.ProductInfoPhoneRes;
import com.hk.Mgr.web.message.order.ProductInfoReq;
import com.hk.Mgr.web.message.order.QueryProductListReq;
import com.hk.base.BaseCtrl;
import com.hk.base.ResponseBase;
import com.hk.commons.*;
import com.hk.commons.enm.ProdStatusEnum;
import com.hk.commons.entity.Agreement;
import com.hk.commons.entity.Answer;
import com.hk.commons.entity.order.OrderContract;
import com.hk.commons.entity.order.OrderInfo;
import com.hk.commons.entity.product.AgreementToProduct;
import com.hk.commons.entity.product.Company;
import com.hk.commons.entity.product.ProductInfo;
import com.hk.commons.entity.sys.SysUser;
import com.hk.commons.vo.CheckInfo;
import com.hk.commons.vo.ProductInfoRes;
import com.hk.service.kyc.IAgreement;
import com.hk.service.order.IOrderContract;
import com.hk.service.order.IOrderInfo;
import com.hk.service.order.impl.OrderHandleContent;
import com.hk.service.product.IAgreementToProduct;
import com.hk.service.product.ICompany;
import com.hk.service.product.IProductInfo;
import com.hk.service.sys.IAnswer;
import com.hk.service.sys.ISysUser;
import com.hk.service.sys.ISysUserRoles;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.*;

/**
 * @author psx 产品信息实现类
 */
@Controller
@RequestMapping(value = BaseCtrl.CommonRootPath + "/ProductInfoCtrl")
public class ComProductInfoCtrl extends BaseCtrl {

	private Logger logger = LoggerFactory.getLogger(ComProductInfoCtrl.class);

	@Autowired
	private IProductInfo productInfoService;

	@Autowired
	private ICompany companyService;

	@Autowired
	private ISysUser userService;

	@Autowired
	private IAnswer anService;

	@Autowired
	private ISysUserRoles userRoleService;

	@Autowired
	private IAgreement aggService;

	@Autowired
	private IOrderInfo orderService;

	@Autowired
	private IOrderContract orderContractService;



	@Autowired
	private OrderHandleContent orderHandleContent;

	@Autowired
	private IAgreementToProduct iAgreementToProduct;

	@Autowired
	private JdbcTemplate jdbcTemplate;

	/**
	 * 手机专用 , 下单前检查，旧版本兼容
	 * 
	 * @Title: getProductInfoList
	 * @Description: 分页获取系统模块
	 * @param
	 */

	@ResponseBody
	@RequestMapping(value = "/checkLimitMsg", method = RequestMethod.POST)
	public ResponseBase<Boolean> checkLimitMsg(@RequestBody ProductInfoPhoneRes req) {
		ResponseBase<Boolean> resp = new ResponseBase<Boolean>();
		logger.info("in checkLimitMsg ");
		if(req == null || req.getUserId() == null ||StringHelper.isEmpty(req.getId())){
			resp.setMsg("参数有误");
			resp.setResultCode(StatusCode.ERROR.key());
			return resp;
		}

		Long userId =  req.getUserId();
		Long prodId = Long.valueOf(req.getId());

		ProductInfo prod = productInfoService.findById(prodId);
		if(prod == null || prod.getParId() == null){
			resp.setMsg("产品不存在，或产品父标不存在！");
			resp.setResultCode(StatusCode.ERROR.key());
			return resp;
		}

		//产品不限购，则默认成功
		if(prod.getLimitNum() == null){
			resp.setResult(true);
			resp.setResultCode(StatusCode.SUCCESS.key());
			return resp;
		}

		Long parId = prod.getParId();


		Integer buyNum = productInfoService.getBuyNum(userId, parId);

		if(buyNum >= prod.getLimitNum() ){
			resp.setResult(false);
			resp.setMsg("该产品限购" + prod.getLimitNum() + "笔， 您已购买" + buyNum + "笔，不能再次购买！");
			resp.setResultCode(StatusCode.ERROR.key());

		}else{
			resp.setResult(true);
			resp.setResultCode(StatusCode.SUCCESS.key());
		}
		return  resp;
	}


	/**
	 * 手机专用, 下单前检查，新
	 *
	 * @Title: getProductInfoList
	 * @Description: 分页获取系统模块
	 * @param
	 */

	@ResponseBody
	@RequestMapping(value = "/check", method = RequestMethod.POST)
    public ResponseBase<Map<String, Object>> check(@RequestBody ProductInfoPhoneRes req, HttpServletRequest request) {
        ResponseBase<Map<String, Object>> resp = new ResponseBase<>();

        Map<String, Object> resultMsg = new HashMap<>();

        logger.info("in check ");
        if (req == null || req.getUserId() == null || StringHelper.isEmpty(req.getId())) {
            resp.setMsg("参数有误");
            resp.setResultCode(StatusCode.ERROR.key());
            return resp;
        }

        Long userId = req.getUserId();
        Long prodId = Long.valueOf(req.getId());

        //检查订单信息，如果通过检查再创建订单，否则不创建订单
        CheckInfo checkInfo;

        String version = req.getV();
        if(StringUtils.isBlank(version)){
            version = request.getParameter("v");
        }

        checkInfo = productInfoService.checkProdBuyVersion(version, "2.6.1", prodId, userId);
        if (checkInfo.getResult() == false) {
            resultMsg.put("errorMsg", checkInfo.getResultMsg());
            resultMsg.put("canBuy", false);
			resultMsg.put("newLocation", ConstantLocation.UPDATE_VERSION);
            resp.setResultCode(StatusCode.SUCCESS.key());
            resp.setResult(resultMsg);
            return resp;
        }

		checkInfo = productInfoService.checkProdBuyKyc(prodId, userId);
        if (checkInfo.getResult() == false) {
            logger.info("checkBeforeCreateOrder, user kyc not finished , can not by prod");
            resultMsg.put("errorMsg", checkInfo.getResultMsg());
            resultMsg.put("canBuy", false);
			resultMsg.put("newLocation", ConstantLocation.DO_KYC);
            resp.setResultCode(StatusCode.SUCCESS.key());
            resp.setResult(resultMsg);

            return resp;
        }


        ProductInfo prod = productInfoService.findById(prodId);
        if (prod == null || prod.getParId() == null) {
			resultMsg.put("errorMsg", "该产品不存在，或产品父标不存在");
			resultMsg.put("canBuy", false);
			resultMsg.put("newLocation", ConstantLocation.NONE);
			resp.setResultCode(StatusCode.SUCCESS.key());
			resp.setResult(resultMsg);
            return resp;
        }

        //检查产品限购
        if (prod.getLimitNum() != null) {
            Long parId = prod.getParId();
            Integer buyNum = productInfoService.getBuyNum(userId, parId);

            if (buyNum >= prod.getLimitNum()) {
                resultMsg.put("errorMsg", "该产品限购" + prod.getLimitNum() + "笔， 您已购买" + buyNum + "笔，不能再次购买！");
                resultMsg.put("canBuy", false);
				resultMsg.put("newLocation", ConstantLocation.NONE);
                resp.setResultCode(StatusCode.SUCCESS.key());
                resp.setResult(resultMsg);
                return resp;
            }
        }

        //待售产品不允许购买
        if (prod.getWaitSale() == null || prod.getWaitSale() == ConstantProduct.PRODUCT_WAITSALE_TRUE) {
            logger.info("该产品未开售，此次购买失败！");
            resultMsg.put("errorMsg", "该产品未开售，此次购买失败！");
            resultMsg.put("canBuy", false);
			resultMsg.put("newLocation", ConstantLocation.NONE);
            resp.setResultCode(StatusCode.SUCCESS.key());
            resp.setResult(resultMsg);
            return resp;
        }


        logger.info("checkBeforeCreateOrder result={}", checkInfo.toString());

        //如果是加息收益产品
        if (prod.getSaleType() == ConstantProduct.PRODUCT_SALETYPE_04) {
            checkInfo = productInfoService.canBuy(userId);
            if (checkInfo.getResult() == false) {
                resultMsg.put("errorMsg", checkInfo.getResultMsg());
                resultMsg.put("canBuy", false);
				resultMsg.put("newLocation", ConstantLocation.NONE);
                resp.setResultCode(StatusCode.SUCCESS.key());
                resp.setResult(resultMsg);
                return resp;
            }
        }

		resultMsg.put("newLocation", ConstantLocation.NONE);
        resultMsg.put("errorMsg", "");
        resultMsg.put("canBuy", true);
        resp.setResultCode(StatusCode.SUCCESS.key());
        resp.setResult(resultMsg);
        return resp;
    }
		/**
         * 手机专用
         *
         * @Title: getProductInfoList
         * @Description: 分页获取系统模块
         * @param
         */
	@ResponseBody
	@RequestMapping(value = "/getList", method = RequestMethod.POST)
	public ResponseBase<List<ProductInfoPhoneRes>> getList(
			@RequestBody ProductInfoPhoneRes req) {
		logger.info("------/getList-在线协议相关---------" + req.toString());
		ResponseBase<List<ProductInfoPhoneRes>> resp = new ResponseBase<List<ProductInfoPhoneRes>>();

		if(req == null || req.getCurPage() == null || req.getPageSize() == null){

			resp.setMsg("参数错误");
			resp.setResultCode(StatusCode.PARAM_ERROR.key());
			return resp;
		}


		String version = req.getVersion();

		logger.info("request versin ={}", version);




		HqlFilter hqlFilter = new HqlFilter();



		logger.info("/ComProductInfoCtrl/getList params: key {}"
				+ " prodTopType = " + req.getProdTopType() + " prodType = "
				+ req.getProdType() + " hotSale = " + req.getHotSale());

		hqlFilter.addSql(" where 1=1");
		// 产品一级类型
		if (StringUtils.isNotEmpty(req.getProdTopType())) {// 固定、浮动、固定+浮动、基金、保险
			hqlFilter.addEQFilter("prodTopType",
					Integer.valueOf(req.getProdTopType()));
		}

		// 产品类型
		if (StringUtils.isNotEmpty(req.getProdType())) {// 股票、债券等等
			hqlFilter.addEQFilter("prodType",
					Integer.valueOf(req.getProdType()));
		}

		// 是否热销
		if (StringUtils.isNotEmpty(req.getHotSale()) && req.getHotSale().equals("1") ) {
			hqlFilter.addLKFilter("topSaleStr", "1");
		}

		Long userId = req.getUserId();

		logger.info("userId = " + userId + " isTest result = " + userService.isTester(userId));


		hqlFilter.addSql(" and isParent = 0 and proStatus = " + ConstantProduct.PRODUCT_RELEASE_STATE_TRUE );


		//检查加息产品是否显示
		Boolean checkResult = true;

		if(req.getUserId() == null ){
			checkResult = false;
		}

		if(StringHelper.isEmpty(version)){
			if(this.productInfoService.canBuy(req.getUserId()).getResult() == true) {
				checkResult = true;
			}else{
				checkResult = false;
			}
		}else{
			checkResult = true;
		}


		logger.info("四五月份活动 check show prod = {}", checkResult);



		// 判断用户是否为测试用户， 如果是则添加测试产品
		// 判断用户是否为测试用户，如果不是则只能看到测试产品
		if (userId == null || userRoleService.isTester(userId) == false) {
			hqlFilter.addSql(" and isTest = " + ConstantProduct.PRODUCT_TYPE_NO_TEST);
		}else{
			logger.info("the user is tester");
		}

		if(checkResult == false){
			hqlFilter.addSql(" and saleType != " + ConstantProduct.PRODUCT_SALETYPE_04);
		}


		/*
		// 升序排列
		hqlFilter.addSql(" order by sequence asc");
		*/
		logger.info("hqlFilter  ={}", hqlFilter.getWhereAndOrderHql());

		Integer curpage = Integer.valueOf(req.getCurPage());
		Integer pageSize = Integer.valueOf(req.getPageSize());

		try {
			/**
			List<ProductInfo> productInfoList = productInfoService
					.findByFilter(hqlFilter, curpage, pageSize);
			 **/

			//获取总的产品列表
			List<ProductInfo> productInfoList = productInfoService.findByFilter(hqlFilter);

			//排序
			Collections.sort(productInfoList);

			//分页获取产品
			//兼容IOS暂时不分页
			List<ProductInfo> returnList  = productInfoService.page(curpage, pageSize, productInfoList);

			//List<ProductInfo> returnList  = productInfoList;


			List<ProductInfoPhoneRes> respPhnoneList = new ArrayList<ProductInfoPhoneRes>();

			// 获取用户的风险等级
			Answer an = null;
			if (userId != null && userService.existById(userId)) {
				SysUser user = userService.findById(userId);
				String mobileId = user.getMobileId();
				if (StringHelper.isNotEmpty(mobileId)) {
					an = anService.getByMobileId(mobileId);
				}
			}

			// 根据模块id查询资源
			if (returnList != null && !returnList.isEmpty()) {
				ProductInfoPhoneRes singleResp = null;
				List<Map<String,Object>> agreements = null;

				for (ProductInfo productInfo : returnList) {
					singleResp =  new ProductInfoPhoneRes();

					// 加入用户的风险等级信息
					if (an != null) {
						singleResp.setUsrRiskLevel(an.getScore());
						singleResp.setUsrRiskDesc(an.getScoreDesc());
					}


					singleResp.setProStatus(productInfo.getProStatus());
					singleResp.setSaleOut(productInfo.getSaleOut());

					singleResp.setBuyChannel(productInfo.getBuyChannel());

					singleResp.setBuyType(productInfo.getBuyType());

					singleResp.setSequence(productInfo.getSequence());

					singleResp.setId(productInfo.getId().toString());

					singleResp.setName(productInfo.getName());


					singleResp.setParId(productInfo.getParId());

					singleResp.setProNo(productInfo.getProNo());

					// 是否可用加息券
					if (productInfo.getUseCard() != null) {
						singleResp.setUseCard(productInfo.getUseCard());
					}
					// 添加风险等级
					if (StringHelper.isNotEmpty(productInfo.getRiskLevel())) {
						singleResp.setRiskLevel(productInfo.getRiskLevel());
					}

					if (productInfo.getProTerm() != null) {
						singleResp.setProTerm(productInfo.getProTermStr());
					}

					if (productInfo.getProdType() != null) {
						singleResp.setProdType(productInfo.getProdType()
								.toString());
					}

					if (productInfo.getProdTopType() != null) {
						singleResp.setProdTopType(productInfo.getProdTopType()
								.toString());
					}

					if(productInfo.getLimitNum() != null){
						singleResp.setLimitNum(productInfo.getLimitNum());
					}

					if(productInfo.getLimitAmount() != null){
						singleResp.setLimitAmount(productInfo.getLimitAmount());
					}

					if (productInfo.getFinancingAccount() != null) {
						singleResp.setFinancingAccount(productInfo
								.getFinancingAccount().toString());
					}

					if(StringHelper.isNotEmpty(productInfo.getLabel01()) && StringHelper.isNotEmpty(productInfo.getLabel01Color01())){
						singleResp.setLabel01(productInfo.getLabel01());
						singleResp.setLabel01Color(productInfo.getLabel01Color01());
					}

					if(StringHelper.isNotEmpty(productInfo.getLabel02()) && StringHelper.isNotEmpty(productInfo.getLabel02Color01())){
						singleResp.setLabel02(productInfo.getLabel02());
						singleResp.setLabel02Color(productInfo.getLabel02Color01());
					}

					if(StringHelper.isNotEmpty(productInfo.getLabel03()) && StringHelper.isNotEmpty(productInfo.getLabel03Color01())){
						singleResp.setLabel03(productInfo.getLabel03());
						singleResp.setLabel03Color(productInfo.getLabel03Color01());
					}

					if(StringHelper.isNotEmpty(productInfo.getLabel04()) && StringHelper.isNotEmpty(productInfo.getLabel04Color01())){
						singleResp.setLabel04(productInfo.getLabel04());
						singleResp.setLabel04Color(productInfo.getLabel04Color01());
					}


					if(productInfo.getWaitSale() != null){
						singleResp.setWaitSale(productInfo.getWaitSale());
					}

					if(productInfo.getActBack() != null){
						singleResp.setActBack(productInfo.getActBack());
					}

					if(StringHelper.isNotEmpty(productInfo.getActFlag())){
						singleResp.setActFlag(productInfo.getActFlag());
					}

					//setBuyType 1:购买， 2：预约
					//waitSale   1:待售， 0：非待售
					//如果产品待售，并且起售时间不为空，则添加起售时间
					if(productInfo.waitSale != null && productInfo.waitSale == ConstantProduct.PRODUCT_WAITSALE_TRUE && productInfo.getChgBuyTypeTime() != null){
						singleResp.setStartSaleTime(productInfo.getChgBuyTypeTime().getTime());
					}

					// 已募集金额
					if (productInfo.getYraiseAccount() != null) {
						BigDecimal maxYarseAccount = productInfo
								.getFinancingAccount();

						if (productInfo.getYraiseAccount().compareTo(
								maxYarseAccount) == 1) {
							singleResp.setYraiseAccount(maxYarseAccount
									.toString());
						} else {
							singleResp.setYraiseAccount(productInfo
									.getYraiseAccount().toString());
						}

					}

					// 剩余额度
					if (productInfo.getSraiseAccount() != null) {

						BigDecimal minSraiseAccount = new BigDecimal("0");
						if (productInfo.getSraiseAccount().compareTo(
								minSraiseAccount) == -1) {
							singleResp.setSraiseAccount(minSraiseAccount
									.toString());
						} else {
							singleResp.setSraiseAccount(productInfo
									.getSraiseAccount().toString());
						}

					}

					// 产品销售状态属性
					if (productInfo.getHotSale() != null) {
						singleResp.setHotSaleStr(ProdStatusEnum
								.getStatus(productInfo.getHotSale()));
					}

					if (productInfo.getIssuerId() != null) {
						singleResp.setIssuerId(productInfo.getIssuerId()
								.toString());
					}

					if (StringHelper.isNotEmpty(productInfo
							.getSubscriptionOrigin())) {
						singleResp.setSubscriptionOrigin(productInfo
								.getSubscriptionOrigin());
					}

					if (productInfo.getMinAppendAccount() != null) {
						singleResp.setMinAppendAccount(productInfo
								.getMinAppendAccount().toString());
					}

					singleResp.setMaxYearRate(productInfo.getMaxYearRate());

					singleResp.setMinYearRate(productInfo.getMinYearRate());

					singleResp.setHotSale(productInfo.getHotSale().toString());


					if (productInfo.getTopSale() != null) {
						singleResp.setTopSale(productInfo.getTopSale()
								.toString());
					}
					
					singleResp.setSaleType(productInfo.getSaleType());

					// 如果是固定收益类
					if (productInfo.getProdTopType().equals(
							Constant.PRODUCT_TYPE_2)) {
						if (productInfo.getMinYearRate().equals(
								productInfo.getMaxYearRate())) {
							singleResp
									.setYearRate(productInfo.getMaxYearRate());
						} else {
							singleResp.setYearRate(productInfo.getMinYearRate()
									+ " ~ " + productInfo.getMaxYearRate());
						}
					} else if (productInfo.getProdTopType().equals(
							Constant.PRODUCT_TYPE_3)) {
						singleResp.setYearRate("浮动收益");
					} else if (productInfo.getProdTopType().equals(
							Constant.PRODUCT_TYPE_4)) {
						singleResp.setYearRate("不低于"
								+ productInfo.getMinYearRate());
					}


//					//如果是额外收益类产品
//					if(productInfo.getSaleType() == ConstantProduct.PRODUCT_SALETYPE_04){
//						singleResp.setYearRate(productInfo.getMaxYearRate()  + "+" +  productInfo.getAddRate());
//
//
//						//BigDecimal resultMinRate = DataHelper.chgPrecentToBigDecimal(productInfo.getMinYearRate()).add(DataHelper.chgPrecentToBigDecimal(productInfo.getAddRate()));
//
//						//BigDecimal resultMaxRate = DataHelper.chgPrecentToBigDecimal(productInfo.getMaxYearRate()).add(DataHelper.chgPrecentToBigDecimal(productInfo.getAddRate()));
//
//
//						singleResp.setMinYearRate(singleResp.getYearRate());
//
//						singleResp.setMaxYearRate(singleResp.getYearRate());
//					}
//
//					//四五月活动控制开始
//					Boolean unNormalDay = productInfoService.checkUnNormalDay();
//					if(unNormalDay && productInfo.getSaleType() != ConstantProduct.PRODUCT_SALETYPE_03){
//						String yearRate = productInfoService.getTotalRateStr(productInfo.getId());
//						singleResp.setYearRate(yearRate);
//						singleResp.setMaxYearRate(yearRate);
//						singleResp.setMinYearRate(yearRate);
//						logger.info("yearRate = {}", productInfoService.getTotalRate(productInfo.getId()));
//					}

					if (productInfo.getProdTopType().equals(
							Constant.PRODUCT_TYPE_2)) {
						String yearRateStr = productInfoService.getTotalRateStr(productInfo.getId());

						logger.info("productName ={}, yearRateStr = {}, yearRate = {}", productInfo.getName(), yearRateStr, productInfoService.getTotalRate(productInfo.getId()).toString());

						singleResp.setYearRate(yearRateStr);

						singleResp.setMaxYearRate(yearRateStr);

						singleResp.setMinYearRate(yearRateStr);
					}



					//如果满标，更改剩余额度和已募集额度
					if(productInfo.getSaleOut()!= null && productInfo.getSaleOut() == 1){
						//logger.info("产品满标 产品名称是={}", productInfo.getName());
						singleResp.setYraiseAccount(productInfo.getFinancingAccount().toString());
						singleResp.setSraiseAccount("0.00");
					}


					//四五月活动控制结束
					Company co = companyService.findById(productInfo
							.getIssuerId());
					singleResp.setIssuer(co.getName());

					respPhnoneList.add(singleResp);

					// 添加产品合同属性
					if (productInfo.getContractId() != null) {
						Agreement agreement = aggService.findById(productInfo
								.getContractId());
						if (agreement != null) {
							singleResp.setContractTitle(agreement.getName());
							singleResp.setContractId(agreement.getId()
									.toString());
						}
					}

					//添加合同属性列表(多个合同)
					List<AgreementToProduct> agreementList = iAgreementToProduct.findByProductId(productInfo.getId());
					if(agreementList == null || agreementList.size()==0){
						Map<String,Object> argeementMap = new HashedMap();
						argeementMap.put("contractId",singleResp.getContractId());
						argeementMap.put("contractTitle",singleResp.getContractTitle());
						argeementMap.put("contractUrl","");
						agreements = new ArrayList<>();
						agreements.add(argeementMap);
						singleResp.setAgreements(agreements);
					}else{
						Map<String,Object> argeementMap;
						agreements = new ArrayList<>();
						for(AgreementToProduct agreement:agreementList){
							argeementMap = new HashedMap();
							argeementMap.put("contractId",agreement.getAgreementId());
							argeementMap.put("contractTitle",agreement.getAgreementTitle());
							argeementMap.put("contractUrl","");
							agreements.add(argeementMap);
						}
						singleResp.setAgreements(agreements);
					}



					// 添加产品父标
					if (productInfo.getParId() != null) {
						ProductInfo proParInfo = productInfoService
								.findById(productInfo.getParId());
						if(proParInfo != null) {
							singleResp.setParName(proParInfo.getName());
						}
					}
				}
			}
			Long total = productInfoService.countByFilter(hqlFilter);
			resp.setSize(total);
			resp.setResultCode(StatusCode.SUCCESS.key());
			resp.setResult(respPhnoneList);
		} catch (Exception ex) {
			logger.error(ex.getMessage(), ex);
			resp.setMsg("操作异常，请重试");
			resp.setResultCode(StatusCode.EXCEPTION.key());
		}

		return resp;
	}

	@ResponseBody
	@RequestMapping(value = "/getProductInfoById", method = RequestMethod.POST)
	public ResponseBase<ProductInfoRes> getProductInfoById(
			@RequestBody ProductInfoReq req) {

		Long productId = req.getId();

		logger.info("getProductInfoById productId = " + productId);

		ResponseBase<ProductInfoRes> resp = new ResponseBase<ProductInfoRes>();

		ProductInfoRes prodRes = productInfoService.getProductInfoResById(productId);

		if (prodRes == null || prodRes.getId() == null) {
			resp.setMsg("产品不存在");
			resp.setResultCode(StatusCode.DATA_NOTEXISTS.key());
			resp.setResult(prodRes);
		} else {
			resp.setResultCode(StatusCode.SUCCESS.key());
			resp.setResult(prodRes);
		}

		return resp;
	}

	@ResponseBody
	@RequestMapping(value = "/query", method = RequestMethod.POST)
	public ResponseBase queryProductList(@RequestBody QueryProductListReq req) {
		ResponseBase responseBase = new ResponseBase();

		List<ProductInfoRes> productResList = new ArrayList<>();
		if (StringUtils.isBlank(req.queryString)) {
			responseBase.setResultCode(ResultCode.PARAM_ERROR.getCode());
			responseBase.setMsg("参数不能为空");
		} else {
			Map<String, String> paramMap = new HashMap<>();
			paramMap.put("低", "R1");
			paramMap.put("较低", "R2");
			paramMap.put("中", "R3");
			paramMap.put("较高", "R4");
			paramMap.put("高", "R5");

			List<Map<String, Object>> resultList = null;

			String sql = null;
			boolean isTester = this.userRoleService.isTester(req.userId);
			if (paramMap.containsKey(req.queryString)) {
				req.queryString = paramMap.get(req.queryString);
				if (isTester) {
					sql = "select * from t_product_info where proStatus = 1 and riskLevel = ? and isParent = 0";
				} else {
					sql = "select * from t_product_info where proStatus = 1 and riskLevel = ? and isTest = 0 and isParent = 0";
				}
				resultList = this.jdbcTemplate.queryForList(sql, new Object[] { req.queryString });
			} else {
				if (isTester) {
					sql = "select * from t_product_info where proStatus = 1 and (proTermStr = ? or riskLevel = ? or name like ?) and isParent = 0";
				} else {
					sql = "select * from t_product_info where proStatus = 1 and isTest = 0 and (proTermStr = ? or riskLevel = ? or name like ?) and isParent = 0";
				}
				resultList = this.jdbcTemplate.queryForList(sql, new Object[] {
						req.queryString, req.queryString, "%" + req.queryString + "%"
				});

				for(Map<String, Object> product :resultList){
					Long productId = Long.valueOf(product.get("id").toString());
					ProductInfoRes productInfoRes = productInfoService.getProductInfoResById(productId);
					productResList.add(productInfoRes);

				}
			}

			responseBase.setResultCode(ResultCode.SUCC.getCode());
			responseBase.setMsg("查询成功");
			responseBase.setResult(productResList);
		}

		return responseBase;
	}

	/**
	 * 获取协议和kyc修改的对应关系，文件命名方式为（挂牌号_身份证号.pdf）
	 * @param request
	 * @param response
	 * @param productNo
	 */
	@RequestMapping(value = "/exportTxt")
	@ResponseBody
	public void exportTxt(HttpServletRequest request,
						  HttpServletResponse response, @RequestParam String productNo){
		StringBuilder sb  = getTxt(productNo);
		FileUtil.exportToTxt(response,"modify",sb);
	}

	/**
	 * 获取文件名称修改对应数据
	 * @param productNo
	 * @return
	 */
	private StringBuilder getTxt(String productNo){
		StringBuilder sb = new StringBuilder();
		ProductInfo productInfo = null ;
		List<OrderInfo> orderInfoList = new ArrayList<>();
		List<Map<String,String>> result  = new ArrayList<>();

		HqlFilter hql = new HqlFilter();
		hql.addEQFilter("proNo",productNo);
		List<ProductInfo> productInfoList = productInfoService.findByFilter(hql);
		if(productInfoList.size() > 0){
			productInfo = productInfoList.get(0);

			if(StringUtils.isNotBlank(productInfo.getListingNumber())){
				//查询某产品的所有订单
				HqlFilter orderHql = new HqlFilter();
				orderHql.addEQFilter("productId",productInfo.getId());
				orderHql.addOrder("id");
				orderInfoList = orderService.findByFilter(orderHql);
			}
		}

		String listingNumber = productInfo.getListingNumber();

		orderInfoList.stream()
				.forEach(orderInfo -> {
					//处理协议
					getContractList(orderInfo.getId(),orderInfo.getUserId(),listingNumber,result);
					getKycStr(orderInfo.getKycPDFUrl(),orderInfo.getUserId(),listingNumber,sb);
				} );

		result.stream().forEach(m -> {
			sb.append(m.get("original"));
			sb.append(",");
			sb.append(m.get("modify"));
			sb.append("\r\n");
		});

		return sb;
	}

	/**
	 * 获取协议列表并拼接成String
	 * @param orderId 订单号
	 * @param userId 用户id
	 * @param listingNumber 挂牌号
	 * @param list 处理结果
	 * @return
	 */
	private void getContractList(Long orderId,Long userId,String listingNumber,List<Map<String,String>> list){
		List<OrderContract> Contractlist = orderContractService.getOrderContractList(orderId);
		SysUser user = userService.findById(userId);
		for (OrderContract  contract :Contractlist){
			String modify = listingNumber+"_"+user.getIdentity()+".pdf";
			//统计用户有没有多次下单
			long repeat =  list.stream()
					.filter(m -> !m.get("orderId").equals(String.valueOf(orderId)) && m.get("modify").contains(user.getIdentity()))
					.count();
			int ceil = (int)Math.ceil(repeat/Contractlist.size());
			if(ceil > 0){
				modify = listingNumber+"_"+user.getIdentity()+"_"+ceil+".pdf";
			}

			Map<String,String> result = new HashMap<>(3);
			result.put("orderId",orderId.toString());
			result.put("original",contract.getContractPDFUrl());
			result.put("modify",modify);
			list.add(result);
		}

	}

	/**
	 * 获取kyc修改后的对应关系
	 * @param kycPDFUrl
	 * @param userId
	 * @param listingNumber
	 * @param result
	 */
	private void getKycStr(String kycPDFUrl,Long userId,String listingNumber,StringBuilder result){
		SysUser user = userService.findById(userId);
		String modify = listingNumber+"_"+user.getIdentity()+".pdf";
		if(result.indexOf(modify) > 0){
			return;
		}
		result.append(kycPDFUrl);
		result.append(",");
		result.append(modify);
		result.append("\r\n");
	}



}
